package com.service.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.common.utils.CloudConstant;
import com.common.baseModel.JsonResult;
import com.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.lang.NonNull;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName ServerProtectInterceptor
 * @Description 拦截器让请求必须走网关/已经改为拦截器了
 * @Author 吃麻椒的花酱
 * @Date 2022/4/4 0:07
 * @Version 1.0
 */
@Slf4j
@Order(-200)
public class ServerProtectInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {

        //如果配置了FALSE 直接放行
       /* if (!CloudSecurityProperties.Only_Fetch_By_Gateway) {
            return true;
        }*/

        String token = request.getHeader(CloudConstant.GATEWAY_TOKEN_HEADER);
        log.info(token);
        String gatewayToken = new String(Base64Utils.encode(CloudConstant.GATEWAY_TOKEN_VALUE.getBytes()));
        log.info(gatewayToken);
        if (StringUtils.equals(gatewayToken, token)) {
            return true;
        } else {
            JsonResult<Object> res = JsonResult.createError("must go through the gateway");
            ServletUtils.sendString(response,new String(JSONObject.toJSONString(res).getBytes()));
            return false;
        }
    }
}